<template>
  <div class="yinpianPrescription-create">
    <div class="yinpianPrescription-name">
      <div class="yinpianPrescription-name-left">
        <el-form :model="submitData.prescription" ref="formName" label-width="80px">
          <el-form-item label="处方名称" prop="prescription_name"
                        :rules="{
            required: true,
            message: '请输入处方名称',
            trigger: 'blur'
          }">
            <el-input
              v-model="submitData.prescription.prescription_name"
              style="width: 400px"
              :disabled="detail=='1'"
              placeholder="请输入处方模板名称"
            ></el-input>
          </el-form-item>
        </el-form>
<!--        <p class="name">处方名称</p>-->
<!--        <el-input-->
<!--          v-model="submitData.prescription.prescription_name"-->
<!--          class="name-input"-->
<!--          :disabled="detail=='1'"-->
<!--          placeholder="请输入处方模板名称"-->
<!--        ></el-input>-->
      </div>
      <!-- <div>{{submitData.prescription.remark[1].js}}</div> -->
    </div>
    <div class="yinpianPrescription-container">
      <div class="yinpianPrescription-info-container">
        <table
          class="info-table"
          border="1"
          width="100%"
          cellspacing="0"
          cellpadding="10"
          style="width: 100%; border-collapse: collapse"
        >
          <tbody>
          <tr class="table-td">
            <td class="table-td" align="center">剂数</td>
            <td class="table-td">
              <div class="jishu">
                <el-input
                  :disabled="detail=='1'"
                  v-model="submitData.prescription.remark[1].js"
                ></el-input>
              </div>
            </td>
            <td class="table-td" align="center">每日剂量</td>
            <td class="table-td mrjl">
              <div class="jishu">
                <el-input
                  :disabled="detail=='1'"
                  v-model="submitData.prescription.remark[1].mrjl"
                ></el-input>
                <p class="unit">剂</p>
              </div>
            </td>
            <td class="table-td" align="center">用药频率</td>
            <td class="table-td">
              <el-autocomplete
                :disabled="detail=='1'"
                class="use-info-input"
                v-model="submitData.prescription.remark[1].yypl"
                :fetch-suggestions="yyplQuerySearch"
                placeholder="用药频率"
                :trigger-on-focus="true"
                @select="
                          (val) => {
                            yyplHandleSelect(val);
                          }
                        "
              >
                <template slot-scope="{ item }">
                  <div class="useage-item">
                    <div class="name">
                      <span>{{ item }}</span>
                    </div>
                  </div>
                </template>
              </el-autocomplete>
            </td>
          </tr>
          <tr class="table-td">
            <td class="table-td" align="center">用法</td>
            <td class="table-td" colspan="5">
              <div>
                <el-autocomplete
                  :disabled="detail=='1'"
                  class="use-info-input"
                  v-model="submitData.prescription.remark[1].yf"
                  :fetch-suggestions="yfQuerySearch"
                  placeholder="用法"
                  :trigger-on-focus="true"
                  @select="
                            (val) => {
                              yfHandleSelect(val);
                            }
                          "
                >
                  <template slot-scope="{ item }">
                    <div class="useage-item">
                      <div class="name">
                        <span>{{ item }}</span>
                      </div>
                    </div>
                  </template>
                </el-autocomplete>
              </div>
            </td>
          </tr>
          <tr class="table-td">
            <td class="table-td" align="center">服用要求</td>
            <td class="table-td" colspan="5">
              <div>
                <el-autocomplete
                  :disabled="detail=='1'"
                  class="use-info-input"
                  v-model="submitData.prescription.remark[1].fyyq"
                  :fetch-suggestions="fyyqQuerySearch"
                  placeholder="服用要求"
                  :trigger-on-focus="true"
                  @select="
                            (val) => {
                              fyyqHandleSelect(val);
                            }
                          "
                >
                  <template slot-scope="{ item }">
                    <div class="useage-item">
                      <div class="name">
                        <span>{{ item }}</span>
                      </div>
                    </div>
                  </template>
                </el-autocomplete>
              </div>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
      <el-form
        :model="submitData"
        ref="patentMedicineValidateForm"
        label-width="100px"
        class="yinpianPrescription-form"
        :disabled="detail=='1'"
      >
        <el-form-item class="form-item-header">
          <div class="top-header">
            <div class="top-left">
              <p>药品</p>
            </div>
          </div>
        </el-form-item>
        <el-table
          :data="submitData.prescription.details"
          border
          style="width: 100%"
          :show-header="false"
        >
          <el-table-column label="药品名称" align="center" width="100px">
            <template slot-scope="scope">
              <div class="item-title">
                <p>饮片{{ scope.$index + 1 }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="饮片名称" width="350px">
            <template slot-scope="scope">
              <el-autocomplete
                class="use-info-input"
                style="width: 350px"
                v-model="scope.row.product_name"
                :fetch-suggestions="ypQuerySearch"
                placeholder="饮片名称"
                :trigger-on-focus="false"
                @change="
                        (val) => {
                          ypDetailChange(val, scope.$index, 'product');
                        }
                      "
                @select="
                      (val) => {
                        ypProHandleSelect(val,scope.$index);
                      }
                    "
              >
                <template slot="suffix" v-if="scope.row.own ? false : true">
                  <el-tooltip
                    v-if="scope.row.product_name!==''"
                    content="该药品不在您的药库中或者库存不足，建议您更换其他药品"
                    placement="bottom"
                    effect="light"
                  >
                    <i class="el-icon-warning"> </i>
                  </el-tooltip>
                </template>
                <template slot-scope="{ item }">
                  <div
                    class="product-item-container"
                    style="
                            display: flex;
                            justify-content: flex-start;
                            align-items: flex-start;
                          "
                  >
                    <div class="icon-container" style="margin-right: 5px">
                      <i
                        class="el-icon-success"
                        style="color: green"
                        v-if="item.Own"
                      ></i>
                      <i class="el-icon-warning" v-else></i>
                    </div>
                    <div class="product-item" style="padding: 5px 0px">
                      <div
                        class="name"
                        style="font-weight: bold; line-height: 22px"
                      >
                              <span class="name-name">{{
                                item.product_name
                              }}</span
                              ><span class="name-pack">({{ item.pack }})</span>
                      </div>
                      <div
                        class="producer"
                        style="color: #999; line-height: 22px"
                      >
                        <span>{{ item.production }}</span>
                      </div>
                    </div>
                  </div>
                </template>
              </el-autocomplete>
            </template>
          </el-table-column>
          <el-table-column label="单剂量" width="100px" align="center">
            <template slot-scope="scope">
              <div class="item-title"><p>单剂量</p></div>
            </template>
          </el-table-column>
          <el-table-column label="单剂量">
            <template slot-scope="scope">
              <el-input
                class="num-input append-input"
                v-model="scope.row.number"
                placeholder="数量"
                @change="
                      (val) => {
                        ypDetailChange(val, scope.$index);
                      }
                    "
                @keyup.native="
                      (val) => {
                        ypNumberChange(val, scope.$index);
                      }
                    "
              >
                <template slot="append">g</template>
              </el-input>
              <!--            <div>-->
              <!--              <el-autocomplete-->
              <!--                class="inline-input"-->
              <!--                v-model="scope.row.single_dose"-->
              <!--                :fetch-suggestions="querySearch"-->
              <!--                placeholder="剂量"-->
              <!--                :trigger-on-focus="false"-->
              <!--                @select="handleSelect"-->
              <!--              >-->
              <!--                <el-select-->
              <!--                  v-model="scope.row.single_unit"-->
              <!--                  slot="append"-->
              <!--                  placeholder="单位"-->
              <!--                >-->
              <!--                  <el-option label="片" value="1"></el-option>-->
              <!--                  <el-option label="粒" value="2"></el-option>-->
              <!--                  <el-option label="克" value="3"></el-option>-->
              <!--                </el-select>-->
              <!--              </el-autocomplete>-->
              <!--            </div>-->
            </template>
          </el-table-column>
          <el-table-column label="备注">
            <template slot-scope="scope">
              <el-autocomplete
                class="use-info-input"
                v-model="scope.row.remark"
                :fetch-suggestions="remarkQuerySearch"
                placeholder="备注"
                :trigger-on-focus="true"
                @select="
                      (val) => {
                        remarkHandleSelect(val, scope.$index);
                      }
                    "
              >
                <template slot-scope="{ item }">
                  <div class="useage-item">
                    <div class="name">
                      <span>{{ item }}</span>
                    </div>
                  </div>
                </template>
              </el-autocomplete>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="30px" v-if="detail!='1'">
            <template slot-scope="scope">
              <div>
                <el-button
                  class="icon-btn"
                  icon="el-icon-delete"
                  @click.prevent="removePatentItem(scope.row)"
                ></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item class="form-item-btn">
          <div class="btn-container">
            <el-button type="text" @click.prevent="addPatentItem(-1)"
            >+新增药品</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
  import { productSearch, productDetail } from "@/api/product.js";
  import publicRemind from "@/assets/js/publicRemind.js";
export default {
  props: {
    editData: {
      type: Object,
      default: null,
    },
    detail:{
      type: String,
    }
  },
  data() {
    return {
      remindData: publicRemind.remind,
      submitData: {
        prescription: {
          prescription_name: "",
          category_key: "ypcf",
          category_name: "饮片处方",
          remark: {
            1: {
              js: "",
              mrjl: "",
              yypl: "",
              yf: "",
              fyyq: "",
            },
          },
          details: [
            {
              own:true,
              product_id: 0,
              product_name: "",
              pack: "", // 规格
              single_dose: "",
              single_unit: "",
              number: "", // 数量
              price: 0, // 价格
              amount: 0, // 总价
              unit: "",
              group: 1,
              remark: "",
            },
          ],
        },
      },
    };
  },
  watch: {
    editData: {
      handler(newval, oldval) {
        if (newval) {
          this.submitData.prescription = this.editData;
          console.log(this.submitData);
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.restaurants = this.loadAll();
    console.log(this.remindData)
  },
  methods: {
    submitForm() {
      var boo;
      this.$refs.formName.validate((valid) => {
        if (valid) {
          boo = true
        } else {
          boo = false;
        }
      });
      return boo
    },
    // 将数据传给父组件
    emitData() {
      return this.submitData;
    },
    async ypProHandleSelect(item, index) {
      let product = await productDetail({ default_id: item.id });
      this.submitData.prescription.details[index].own = product.data
        ? true
        : item.Own;
      this.submitData.prescription.details[index].product_id = product.data
        ? product.data.id
        : item.id;
      this.submitData.prescription.details[index].product_name = product.data
        ? product.data.product_name
        : item.product_name;
      this.submitData.prescription.details[index].pack = product.data
        ? product.data.pack
        : item.pack;
      this.submitData.prescription.details[index].unit = product.data
        ? product.data.number_unit
        : item.number_unit;
      this.submitData.prescription.details[index].price = product.data
        ? Number(product.data.price)
        : Number(item.price || 0);
      this.submitData.prescription.details[index].number = 1;
      let price = this.submitData.prescription.details[index].price;
      let num = this.submitData.prescription.details[index].number;
      this.submitData.prescription.details[index].amount = price * num;
    },
    ypDetailChange(val, index, type) {
      if (type == "product") {
        this.submitData.prescription.details[index].own = false;
      }else if(this.submitData.prescription.details[index].stock<=0){
        this.submitData.prescription.details[index].own = false
        this.submitData.prescription.details[index].price = 0
      }
      if (this.submitData.prescription.details[index].update_status !== 2) {
        this.submitData.prescription.details[index].update_status = 1;
      }
    },
    ypNumberChange(val, index, idx) {
      let price = this.submitData.prescription.details[index].price;
      let num = this.submitData.prescription.details[index].number;
      this.submitData.prescription.details[index].amount = price * num;
    },
    // 饮片detail改变---改变更新状态
    // ypDetailChange(val, index, idx) {
    //   if (this.submitData.prescription.details[index].update_status !== 2) {
    //     this.submitData.prescription.details[index].update_status = 1;
    //   }
    // },
    commonCreateFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    // 饮片用药频率输入联想--开始
    yyplQuerySearch(queryString, cb) {
      var restaurants = this.remindData.eat_rate;
      var results = queryString
        ? restaurants.filter(this.commonCreateFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    yyplHandleSelect(val, index) {
      this.submitData.prescription.remark[1].yypl = val;
    },
    // 饮片用法输入联想--开始
    yfQuerySearch(queryString, cb) {
      var restaurants = this.remindData.yinpian_useage;
      var results = queryString
        ? restaurants.filter(this.commonCreateFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    yfHandleSelect(val, index) {
      this.submitData.prescription.remark[1].yf = val;
    },
    // 服用要求输入联想--开始
    fyyqQuerySearch(queryString, cb) {
      var restaurants = this.remindData.require;
      var results = queryString
        ? restaurants.filter(this.commonCreateFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    fyyqHandleSelect(val, index) {
      this.submitData.prescription.remark[1].fyyq = val;
    },
    // 备注要求输入联想--开始
    remarkQuerySearch(queryString, cb) {
      var restaurants = this.remindData.advice;
      var results = queryString
        ? restaurants.filter(this.commonCreateFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    remarkHandleSelect(val, index, idx) {
      this.submitData.prescription.details[index].remark = val;
    },
    // 饮片产品联想
    async ypQuerySearch(queryString, cb) {
      let pro = await productSearch({
        prefix: queryString,
        size: 10,
        condition: {
          category_id: "1",
        },
      });
      this.ypProductList = pro.data.ElasticProduct || [];
      var results = this.ypProductList;
      cb(results);
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    removePatentItem(item) {
      var index = this.submitData.prescription.details.indexOf(item);
      if (index !== -1) {
        this.submitData.prescription.details.splice(index, 1);
      }
    },
    addPatentItem(index) {
      console.log(index);
      if (index == -1 || index == this.submitData.prescription.details.length - 1) {
        this.submitData.prescription.details.push({
          own:true,
          product_id: 0,
          product_name: "",
          pack: "", // 规格
          single_dose: "",
          single_unit: "",
          number: "", // 数量
          price: 0, // 价格
          amount: 0, // 总价
          unit: "",
          group: 1,
          remark: "",
          key: Date.now(),
        });
      }
    },
    handleSelect(item) {
      console.log(item);
    },
    loadAll() {
      return [
        { value: "三全鲜食（北新泾店）", address: "长宁区新渔路144号" },
        {
          value: "Hot honey 首尔炸鸡（仙霞路）",
          address: "上海市长宁区淞虹路661号",
        },
        {
          value: "新旺角茶餐厅",
          address: "上海市普陀区真北路988号创邑金沙谷6号楼113",
        },
        { value: "泷千家(天山西路店)", address: "天山西路438号" },
        {
          value: "胖仙女纸杯蛋糕（上海凌空店）",
          address: "上海市长宁区金钟路968号1幢18号楼一层商铺18-101",
        },
        { value: "贡茶", address: "上海市长宁区金钟路633号" },
        {
          value: "豪大大香鸡排超级奶爸",
          address: "上海市嘉定区曹安公路曹安路1685号",
        },
        {
          value: "茶芝兰（奶茶，手抓饼）",
          address: "上海市普陀区同普路1435号",
        },
        { value: "十二泷町", address: "上海市北翟路1444弄81号B幢-107" },
        { value: "星移浓缩咖啡", address: "上海市嘉定区新郁路817号" },
        { value: "阿姨奶茶/豪大大", address: "嘉定区曹安路1611号" },
        { value: "新麦甜四季甜品炸鸡", address: "嘉定区曹安公路2383弄55号" },
      ];
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/templates/modules/yinpianPrescription.scss";
</style>
<style>
  .yinpianPrescription-create .el-input__suffix {
    position: absolute;
    height: 100%;
    right: 5px;
    top: 8px;
    text-align: center;
    color: #D23137;
    transition: all 0.3s;
    pointer-events: none;
  }
</style>
